package com.xuecheng.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.constants.CompanyConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CompanyApproveDto;
import com.xuecheng.commons.model.dto.CompanyDto;
import com.xuecheng.commons.model.dto.CompanyListDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.vo.CompanyVo;
import com.xuecheng.commons.model.vo.PageResponseResult;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.system.domain.Company;
import com.xuecheng.system.mapper.CompanyMapper;
import com.xuecheng.system.service.CompanyService;
import com.xuecheng.system.service.UserService;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 教育机构 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-29
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {

    @Autowired//依赖注入用户service
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override//    机构资料提交(新增或者更新)
    public ResponseResult saveOrUpdateCompany(CompanyDto dto) {
//        1.检验传入参数是否为空
        if (StrUtil.isEmpty(dto.getPhone())) {
            throw new BusinessException(ErrorCode.PARAMSERROR);//如果必填字段为空,返回错误信息
        }
        //校验验证码
        // 1.比较验证码是否正确
        // 1-1 取出redis
        String codeFromRedis = (String) redisTemplate.opsForValue().get("code:" + dto.getPhone());
        // 1-2 比较
        if (!StrUtil.equals(dto.getVerifyCode(), codeFromRedis)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
//        2.属性复制给实体类company
        Company company = BeanHelper.copyProperties(dto, Company.class);
//        2.1补充字段(状态,审核状态等)
//        3.根据租户id和营业执照注册号判断数据库中是否已有,有的话判断审核状态,没有的话新增或者更新
        LambdaQueryWrapper<Company> qw = new LambdaQueryWrapper<>();//创建机构的条件
        qw.eq(Company::getBusinessRegistNo, dto.getBusinessRegistNo());//条件:营业执照注册号相同
        Company company1 = this.getOne(qw);//查询出符合条件的数据
        if (company1 != null && company1.getApprovalStatus().equals(CompanyConstants.AUDIT_COMMIT_STATUS)) {//如果有相似的判断数据审核状态,如果已审核不能修改
//        3.1如果该数据不为空并且已审核,返回错误信息
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
//        3.2补充字段,状态 创建时间和审核状态
        company.setCreateDate(DateUtil.date());
        company.setStatus(CompanyConstants.AUDIT_WEIXIAOSHUAI_STATUS);//修改为-1
        company.setApprovalStatus(CompanyConstants.AUDIT_UNPAST_STATUS);//审核状态为未审核
//        3.3新增或更新到数据库
        this.saveOrUpdate(company);
//        4.返回信息
        return ResponseResult.okResult();
    }

    @Override//    平台管理查询机构列表///平台查询机构审核列表
    public ResponseResult findCompanyList(PageRequest parms, CompanyListDto dto) {

//
        /*判断map是否为空*/
        //String approvalStatus  = map.get("approvalStatus");
        String approvalStatus = dto.getApprovalStatus();

        //判断是否为3
        //为3,列表
        //不为3,审核
        if (approvalStatus != "202003") {//1.查询待审核列表,符合状态的所有数据

            //1.构建分页(排序分组等未添加)
            Page<Company> page = new Page<>(parms.getPageNo(), parms.getPageSize());
            List<String> list = Arrays.asList(approvalStatus.split(","));

            LambdaQueryWrapper<Company> statusQw = new LambdaQueryWrapper<>();
            statusQw.in(Company::getApprovalStatus, list);
            page = this.page(page, statusQw);
//        2.将list转换为vo
            List<Company> companyList = page.getRecords();
//        3.调用工具类复制属性
            List<CompanyVo> vo = BeanHelper.copyWithCollection(companyList, CompanyVo.class);
            if (CollectionUtil.isNotEmpty(vo)) {
                for (CompanyVo companyVo : vo) {
                    companyVo.setCompanyId(companyVo.getId().toString());
                }
            }

//        4.返回分页结果
            //long counts = page.getTotal();
            return PageResponseResult.okResult(page.getTotal(), vo);
        } else {
            //下面是第二种判断
            //如果map为空就是机构列表查询
//        2.构建条件 (审核状态,机构名称)
            //1.构建分页(排序分组等未添加)
            Page<Company> page = new Page<>(parms.getPageNo(), parms.getPageSize());
//        2.1创建条件
            LambdaQueryWrapper<Company> qw = new LambdaQueryWrapper<>();
//        2.2条件:机构名称不为空的话,模糊查询
            qw.like(StrUtil.isNotBlank(dto.getCompanyName()), Company::getName, dto.getCompanyName());
//        条件:状态不为空的话,对比查询
            qw.eq(StrUtil.isNotBlank(dto.getApprovalStatus()), Company::getApprovalStatus, dto.getApprovalStatus());
//        2.3查询数据库符合条件个数
            //long count = this.count(qw);
//        3.执行分页查询
            page = this.page(page, qw);
//        4.转换为vo
            List<Company> companyList = page.getRecords();
//        调用工具类复制属性
            List<CompanyVo> vo = BeanHelper.copyWithCollection(companyList, CompanyVo.class);
            //long counts = page.getTotal();
            if (CollectionUtil.isNotEmpty(vo)) {
                for (CompanyVo companyVo : vo) {
                    companyVo.setCompanyId(companyVo.getId().toString());
                }
            }
//        5.返回分页结果
            return PageResponseResult.okResult(page.getTotal(), vo);
        }
    }

    @Override//    审核机构资料(根据id然后修改数据的审批状态和审批意见
    public ResponseResult approve(CompanyApproveDto dto) {//接收参数审批意见,审批状态.公司id值
//        1.创建条件
        LambdaQueryWrapper<Company> qw = new LambdaQueryWrapper<>();
        qw.eq(Company::getId, dto.getCompanyId());//id相同
        Company company = this.getOne(qw);//查询数据库找到该id
//        2.修改参数
        company.setApprovalComment(dto.getApprovalComment());//审批意见
        company.setApprovalStatus(dto.getApprovalStatus());//修改审批状态
        company.setApprovalNums(company.getApprovalNums() + 1);//修改审批次数
        company.setApprovalDate(DateUtil.date());//修改审批日期
//        2.1修改审批人
        /*Long userId = AuthInfoHolder.getUserId();
        User user = userService.getById(userId);
        String utype = user.getUtype();*/
        company.setApprovalPeople("xc-operation-admin");
//        3.更新到数据库
        this.updateById(company);
        return ResponseResult.okResult();
    }

    @Override//    平台管理根据id查询企业
    public ResponseResult findByCompanyId(String id) {//参数企业id
//        1.对参数进行非空判断
        if (StrUtil.isEmpty(id)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);//如果为空返回错误信息
        }
//        2.调用数据库查询数据
        long companyId = Long.parseLong(id);
        Company company = this.getById(companyId);
        if (company == null) {//如果数据库查询不到返回错误信息
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
//        3.复制属性类
        CompanyVo vo = BeanHelper.copyProperties(company, CompanyVo.class);
//        4.返回vo
        return ResponseResult.okResult(vo);
        // return null;
    }
}
